package com.gis.controller;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import com.gis.dto.SLDStyleDto;
import com.gis.entity.ColorMapEntry;
import com.gis.entity.GeoServerStyle;
import com.gis.entity.SLDStyle;
import com.gis.result.ResponseResult;
import com.gis.service.GeoServerRestApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;



@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/file")
@Tag(name = "Geoserver REST 接口", description = "Geoserver REST API接口")
public class GeoserverRESTAPIController {

    @Value("${files.dir}/${files.relative-save-dir}/${files.netcdf}")
    private String netcdfDir;

    @Value("${gis.geoserver.workspace}")
    private String workSpaceName;

    

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("upload_file")
    public ResponseResult<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        //TODO: process POST request
        Map<String, Object> result = new HashMap<>();
        try {

            // 获取文件信息
            String originalFilename = file.getOriginalFilename();
            String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            Long size = file.getSize();

            // 日志记录
            log.info("originalFilename: " + originalFilename);
            log.info("type: " + type);
            log.info("size: " + size);

            File destDir = new File(netcdfDir);
            // 判断文件路径是否为存在
            if (!destDir.exists()) {
                destDir.mkdirs();
            }

            // 保存文件
            String uuid = UUID.randomUUID().toString();
            File uploadFile = new File(destDir + "/" + uuid + "_" + originalFilename);
            file.transferTo(uploadFile);
            
            
            // 返回结果
            result.put("originalFilename", originalFilename);
            result.put("type", type);
            result.put("size", size);


            return ResponseResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("error", e.getMessage());
            result.put("message", "上传失败");
            return ResponseResult.fail(result);
        }
    }

    @PostMapping("addStoreData")
    public ResponseResult<Map<String, Object>> addStoreData(@RequestParam("filename") String originalFilename) {
        //TODO: process POST request
        Map<String, Object> result = new HashMap<>();
        try {
            String FileDir =  netcdfDir + "/" + originalFilename;
            String FileUrl = "file://" + FileDir;
            String workspaceName = this.workSpaceName;
            // String storeName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String storeName = "netcdfstore";
            
            // 设置请求头
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-type", "application/json");
            requestHeaders.setBasicAuth("admin", "geoserver");
            
            // 设置请求体
            Map<String, Object> requestBoody = new HashMap<>();
            requestBoody.put("coverageStore", new HashMap<String, Object>() {{
                put("name", storeName);
                put("url", FileUrl);
                put("type", "NetCDF");
                put("enabled", true);
                put("workspace", new HashMap<String, Object>() {{
                    put("name", workspaceName);
                }});
                put("__default__", false);
            }});

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBoody, requestHeaders);
            

            // 发送请求
            String url = "http://localhost:8090/geoserver/rest/workspaces/" + workspaceName + "/coveragestores";


            // 查看返回值；201表示创建成功  
            String response = restTemplate.postForObject(url, requestEntity, String.class);
            log.info("response: " + response);
        }catch (Exception e) {
            e.printStackTrace();
            result.put("error", e.getMessage());
            result.put("message", "添加失败");
            return ResponseResult.fail(result);
        }
        return ResponseResult.success(result);
    }

    @PostMapping("addLayer")
    public ResponseResult<Map<String, Object>> addLayer(@RequestParam("storename") String storename, @RequestParam("layername") String layername, @RequestParam("nativename") String nativename) {
        Map<String, Object> result = new HashMap<>();
        
        try{
            String workspaceName = this.workSpaceName;;
            String url = "http://localhost:8090/geoserver/rest/workspaces/" + workspaceName + "/coveragestores/" + storename + "/coverages";

            // 设置请求头
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-type", "application/json");
            requestHeaders.setBasicAuth("admin", "geoserver");
            
            
            // 设置请求体
            Map<String, Object> requestBoody = new HashMap<>();
            requestBoody.put("coverage", new HashMap<String, Object>() {{
                put("name", layername);
                put("nativeName", nativename);
                put("title", layername);
                put("enable", true);
            }});

            // 整合请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBoody, requestHeaders);
            
            // 发送请求
            String response = restTemplate.postForObject(url, requestEntity, String.class);
            
            // 查看返回值；201表示创建成功
            log.info("response: " + response);
            result.put("response", response);

        }catch (Exception e) {
            e.printStackTrace();
            result.put("error", e.getMessage());
            result.put("message", "添加失败");
            return ResponseResult.fail(result);
        }

        return ResponseResult.success(result);
    }
    
    @PostMapping("modifydefaultStyle")
    public ResponseResult<Map<String, Object>> modifydefaultStyle(@RequestParam("layername") String layername, @RequestParam("stylename") String stylename) {
        Map<String, Object> result = new HashMap<>();
        
        try{
            String workspaceName = this.workSpaceName;;
            String url = "http://localhost:8090/geoserver/rest/layers/" + workspaceName + ":" + layername;

            // 设置请求头
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-type", "application/json");
            requestHeaders.setBasicAuth("admin", "geoserver");
            
            
            // 设置请求体
            Map<String, Object> requestBoody = new HashMap<>();
            requestBoody.put("layer", new HashMap<String, Object>() {{
                put("defaultStyle", new HashMap<String, Object>() {{
                    put("name", stylename);
                }});
            }});

            // 整合请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBoody, requestHeaders);
            
            // 发送请求
            String response = restTemplate.exchange(url, org.springframework.http.HttpMethod.PUT, requestEntity, String.class).getBody();
            
            // 查看返回值；201表示创建成功
            log.info("response: " + response);
            result.put("response", response);

        }catch (Exception e) {
            e.printStackTrace();
            result.put("error", e.getMessage());
            result.put("message", "添加失败");
            return ResponseResult.fail(result);
        }

        return ResponseResult.success(result);
    }

    
    
}
